﻿using Aop.Api.Domain;
using BuyWithoutLoseMoney;
using BuyWithoutLoseMoney.Core.Models;
using BuyWithoutLoseMoney.Core.Repositories;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System;
using System.Linq;
using System.Threading.Tasks;
using System.Xml.Linq;

namespace BuyWithoutLose.Areas.Admin.Controllers
{
    /// <summary>
    /// 新闻
    /// </summary>
    [Area("admin")]
    public class NewController : BaseAdminController
    {
        private readonly IRepository<News, int> _newRepository;
        private readonly IRepository<NewsType, int> _newTypeRepository;
        public NewController(IRepository<News,int> newRepository,IRepository<NewsType,int> newTypeRepository, BuyWithoutLoseMoneyDBContext db) : base(db)
        {
            _newRepository = newRepository;
            _newTypeRepository = newTypeRepository;
        }
        #region 新闻列表展示，查询，修改，删除
        /// <summary>
        /// 新闻列表展示
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async  Task<IActionResult> Index()
        {
            var news=await _newRepository.GetAllListAsync();
            var newtypes=await _newTypeRepository.GetAllListAsync();
            ViewBag.newtypes = newtypes;
            return View(news);
        }
        /// <summary>
        /// 新闻列表的查询
        /// </summary>标题和作者，分类
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> Index(int page, int limit,string title,string author,int newTypeId=0)
        {

            var news = _newRepository.GetAll();
            var query = news.Include("NewsType").Where(x => true);
            
            //搜索标题
            if (!string.IsNullOrEmpty(title))
            {
                query = query.Where(x => x.Title.Contains(title));
            }
            //搜索作者
            if (!string.IsNullOrEmpty(author))
            {
                query = query.Where(x => x.Author.Contains(author));
            }
            //分类Id
            if (newTypeId != 0)
            {
                query = query.Where(x => x.NewsTypeId == newTypeId);
            }
            var count = query.Count();
            var list = query.OrderBy(x => x.Id).Skip((page - 1) * limit).Take(limit).ToList()
               .Select(x => new
               {
                   id = x.Id,
                   title = x.Title,
                   subtitle = x.SubTitle,
                   //content = x.Content,
                   createtime = x.CreateTime.ToString(),
                   author = x.Author,
                   newType = x.NewsType.Name,
                   status=x.Status,
                 }) ; 
            return Json(new { Code = 0, Msg = "", Data = list, Count = count });
        }
        /// <summary>
        /// 添加新闻
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> Create()
        {
            var news=await _newRepository.GetAllListAsync();
            ViewBag.News = news;
            var newTypes=await _newTypeRepository.GetAllListAsync();
            ViewBag.NewTypes = newTypes;
           return View();
        }
        [HttpPost]
        public async Task<IActionResult> Create(News news)
        {
            //news.CreateTime = DateTime.Now;
            if (ModelState.IsValid)
            {
                await _newRepository.InsertAsync(news);
                return Json(new { isSuccess = true, msg = "添加成功，页面即将刷新！" });
            }
            return Json(new { isSuccess = false, msg = "添加失败，页面即将返回！" });
        }
        /// <summary>
        /// 修改新闻
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> Edit(int id)
        {
            var news=await _newRepository.GetAllListAsync();
            var s= news.FirstOrDefault(x => x.Id == id);
            var newtype=await _newTypeRepository.GetAllListAsync();
            ViewBag.newType=newtype;
            return View(s);
        }
        [HttpPost]
        public async Task<IActionResult> Edit(News news)
        {
            if (ModelState.IsValid)
            {
                await _newRepository.UpdateAsync(news);
                return Json(new { isSuccess = true, msg = "修改成功，页面即将刷新！" });
            }
            return Json(new { isSuccess = false, msg = "修改失败，请重试！" });
        }
        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<IActionResult> Del(int id)
        {
            News p = new News() { Id = id };
            if (ModelState.IsValid)
            {
                await _newRepository.DeleteAsync(p);
                return Json(new { isSuccess = true, msg = "修改成功，页面即将刷新！" });
            }
            return Json(new { isSuccess = false, msg = "删除失败，请重试！" });
        }
        #endregion
    }
}
